/*! @file providerdlg.cpp
 * @brief Implements ProviderDlg Class
 * @date 10.09.2012
 */

#include "providerdlg.h"

#include <QCheckBox>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QFile>
#include <QListView>
#include <QListWidgetItem>
#include <QMenu>
#include <QMessageBox>
#include <QRegExp>
#include <QSettings>
#include <QUrl>

/**
 * @brief ProviderDlg::ProviderDlg
 * @param provider
 * @param parent
 * @callgraph
 * @callergraph

 */
ProviderDlg::ProviderDlg(QList<QString> provider, QWidget *parent) :
    QDialog(parent)
{
    QList<QString> lastProviders;

    setupUi(this);

    providerList->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(okButton, SIGNAL(clicked()),
            this, SLOT(on_okButtonClicked()));
    connect(providerSearchEdit, SIGNAL(textChanged(QString)),
            this, SLOT(on_FilterProviderList(QString)));
    connect (providerList, SIGNAL ( customContextMenuRequested(const QPoint &)),
             this, SLOT(showContextMenu(const QPoint &)));


    // setting models
    model = new QStandardItemModel(provider.size(), 2);
    proxy = new QSortFilterProxyModel(this);
    proxy->setSourceModel(model);
    proxy->setFilterKeyColumn(0);
    QRegExp regExp("*", Qt::CaseInsensitive, QRegExp::Wildcard);
    proxy->setFilterRegExp(regExp);

    // read lastProviders from ini file
    QString templateFile = QDir::toNativeSeparators(QApplication::applicationDirPath ()
                                                    + "/templates/PPSettings.ini");
    QSettings settings (templateFile, QSettings::IniFormat);
    settings.beginGroup("LastProviders");
    QVariantList vList = settings.value("lastProviders").toList();
    for(int i=0; i<vList.size(); ++i)
        lastProviders.append(vList.at(i).toString());
    qDebug() << "ProviderDlg\t|lastProviders:" << lastProviders;


    // build tree and select last choosen providers from ini
    for(int i=0; i<provider.size()-1; ++i) {
        QStandardItem *item = new QStandardItem;
        item->setCheckable(true);
        item->setText(QString(provider.at(i)).remove('\n').remove('\r'));
        Q_FOREACH(QString lp, lastProviders) {
            QRegExp rx("^" + lp.simplified() + "$");
            if(provider.at(i).simplified().contains(rx)) {
                item->setCheckState(Qt::Checked);
            }
        }
        model->setItem(i, item);
    }
    providerList->setModel(model);
}

/**
 * @brief ProviderDlg::onFilterProviderList
 * @param filter
 */
void ProviderDlg::on_FilterProviderList(QString filter)
{
    filter = QString("*") + filter + QString("*");
    QRegExp regExp(filter, Qt::CaseInsensitive, QRegExp::Wildcard);
    proxy->setFilterRegExp(regExp);
    providerList->setModel(proxy);

    qDebug() << "ProviderDlg\t|fitered results:" << filter << providerList->model()->rowCount();
}

/**
 * @brief ProviderDlg::on_okButtonClicked
 */
void ProviderDlg::on_okButtonClicked()
{
    QList<QString> selProviders;
    QAbstractItemModel *itemModel = providerList->model();

    // get selected providers
    for(int i=0; i<itemModel->rowCount(); ++i ) {
        if(itemModel->index(i, 0).data(Qt::CheckStateRole).toBool())
            selProviders << itemModel->index(i, 0).data(Qt::DisplayRole).toString().simplified();
    }

    qDebug() << "ProviderDlg\t|selProviders:" << selProviders;

    Q_EMIT providersReady(selProviders);
}

/** @brief context menu wtf is this
 * @callgraph
 * @callergraph
 */
void ProviderDlg::rightBtnWhatsThatAct()
{
    QItemSelectionModel *selectionModel = providerList->selectionModel();
    QString package = selectionModel->currentIndex().data().toString().remove('\n').remove('\r');
    QUrl url = "https://play.google.com/store/apps/details?id="+package+"&hl=de";
    bool success = false;

    if(url.isValid())
        success = QDesktopServices::openUrl(url);
    if(success)
        qDebug() << url << "opened in Standardbrowser";
    else
        qDebug() << "ProviderDlg\t|cannot open url:" << url.toString();
}

/** @brief show context menu
 * @callgraph
 * @callergraph
 */
void ProviderDlg::showContextMenu(const QPoint & pos)
{
    Q_UNUSED(pos);

    QMenu contextMenu(this);

    contextMenu.addAction ( tr("wtf ist das"),
                            this, SLOT (rightBtnWhatsThatAct()) );
    contextMenu.exec( QCursor::pos() );
}

